package com.huzz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huzz.entity.SysPermission;
import com.huzz.entity.SysRole;
import com.huzz.mapper.SysPermissionMapper;
import com.huzz.model.PermissionModel;
import com.huzz.service.ISysPermissionService;
import com.huzz.service.ISysRoleService;
import com.huzz.util.entityutil.ModelUtil;
import com.huzz.util.tree.TreeBuilder;
import com.huzz.vo.PermissionVO;
import com.huzz.util.body.DataBox;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Name 名称
 * @Description 描述
 * @Author 童年的纸飞机
 * @Since 2023-04-2023/4/27 11:14
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {

    @Autowired
    private SysPermissionMapper permissionMapper;

    @Override
    public DataBox<String> createPermission(PermissionModel permissionModel) {
        return DataBox.builder(permissionMapper.insert(ModelUtil.transToSimilarEntity(permissionModel, SysPermission.class)) > 0, "新建成功", "新建失败");
    }

    @Override
    public IPage<PermissionVO> findPermissionListPage(Integer pageNum, Integer pageSize, PermissionModel model) {
        QueryWrapper<SysPermission> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(model.getName())) {
            wrapper.lambda().like(SysPermission::getName, model.getName());
        }
        return TreeBuilder.builderIPageTree(permissionMapper, new Page<>(pageNum, pageSize), wrapper, PermissionVO.class);
    }

    @Override
    public DataBox<String> updatePermissionById(SysPermission permission) {
        if (permission.getId() == null) {
            return DataBox.failedBuilder("权限id不能为空");
        }
        return DataBox.builder(permissionMapper.updateById(permission) > 0, "更新成功", "更新失败");
    }

    @Override
    public DataBox<String> removePermissionById(Integer id) {
        if (id == null) {
            return DataBox.failedBuilder("权限id不能为空");
        }
        return DataBox.builder(permissionMapper.deleteById(id) >0, "删除成功", "删除失败");
    }

    @Autowired
    private ISysRoleService roleService;

    @Override
    public List<SysPermission> findPermissionListByUserId(Integer userId) {
        List<SysRole> roleList = roleService.findRoleListByUserId(userId);
        List<Integer> roleIdList = roleList.stream().map(m -> m.getId()).collect(Collectors.toList());
        if (roleIdList.isEmpty()) {
            return new ArrayList<>();
        }

        return permissionMapper.findPermissionListByRoleIds(roleIdList);
    }
}
